// 载入 ws 库
const WebSocketServer = require('ws')
const jsonData = require("./data/shuziren")

const serverPort = 8085;


// 创建一个 websocket 服务
const wss = new WebSocketServer.Server({port: serverPort})
// 返回消息的索引
let dataIndex = 0

// 创建连接
wss.on("connection", ws => {
    // 每次客户端连接索引增加，超过7归零
    if (dataIndex > 6) {
        dataIndex = 0;
    }
    let message = jsonData[dataIndex].keys
    console.log("新客户端已连接,本次返回消息：", message)
    let resData = {results: [{is_final: true, alternatives: [{transcript: message}]}]}
    dataIndex++
    // 接收到 client 数据时
    ws.on("message", data => {
        const res = JSON.stringify(resData)
        console.log("res--", res)
        ws.send(res)
        ws.close()
    })
    ws.on("close", () => {
        console.log("websocket server: 客户端已关闭连接")
    })
    ws.onerror = function () {
        console.log("websocket server: 出错了")
    }
})
console.log(`websocket 服务已运行在端口 ${serverPort}`)